﻿using System.Collections.Generic;
using System.Threading.Tasks;
using BookSleeve;

namespace Inovout.YunYao.Cattle.WindowsService
{
    public class QueueManager
    {
        public string RedisIP { get; private set; }
        public int RedisPort { get; private set; }
        public int RedisTableId { get; private set; }
        public string QueueName { get; private set; }
        public QueueManager(string redisIP, int redisPort, int redisTableId, string queueName)
        {
            RedisIP = redisIP;
            RedisPort = redisPort;
            RedisTableId = redisTableId;
            QueueName = queueName;
        }
        public string[] CopyTo(string destinationQueueName, int count)
        {
            using (var redisConnection = new RedisConnection(RedisIP, RedisPort))
            {
                Task<string>[] tasks = new Task<string>[count];
                redisConnection.Open();
                for (int i = 0; i < count; i++)
                {
                    tasks[i] = redisConnection.Lists.RemoveLastAndAddFirstString(RedisTableId, QueueName, destinationQueueName);
                }
                string[] queues = new string[count];
                for (int i = 0; i < count; i++)
                {
                    tasks[i].Wait();
                    queues[i] = tasks[i].Result;
                    tasks[i].Dispose();
                }
                return queues;
            }
        }
        public long Count()
        {
            using (var redisConnection = new RedisConnection(RedisIP, RedisPort))
            {
                redisConnection.Open();
                using (var redisTask = redisConnection.Lists.GetLength(RedisTableId, QueueName))
                {
                    redisTask.Wait();
                    return redisTask.Result;
                }
            }
        }
        public string[] Receive(int start, int stop)
        {
            using (var redisConnection = new RedisConnection(RedisIP, RedisPort))
            {
                redisConnection.Open();
                using (var task = redisConnection.Lists.RangeString(RedisTableId,
                    QueueName, start, stop, true))
                {
                    task.Wait();
                    return task.Result;
                }
            }
        }
        public Task Remove(string key, int start, int stop)
        {
            using (var redisConnection = new RedisConnection(RedisIP, RedisPort))
            {
                redisConnection.Open();
                return redisConnection.Lists.Trim(RedisTableId,
                    key, stop + 1, -1 - start, true);

            }
        }
        public Task Remove(int start, int stop)
        {
            return this.Remove(QueueName, start, stop);
        }
    }
}
